//创建用户相关的小仓库
import {defineStore} from 'pinia'
//引入接口
import {reqLogin, reqLogout, reqUserInfo} from '../../api/user';
//引入路由（常量路由）
import {constantRoute} from '../../router/routes.ts'
import {ref} from "vue";
import type {loginFormData, loginResponseData, userInfoResponseData} from "../../api/user/type.ts";

//创建用户小仓库
const useUserStore = defineStore('User', () => {
    let token = ref(localStorage.getItem("token"));
    let menuRoutes = ref(constantRoute);
    let username = ref();
    let avatar = ref();


    //用户登录的方法
    async function userLogin(data: loginFormData) {
        //登录请求
        const result: loginResponseData = await reqLogin(data)

        if (result.code == 200) {
            //pinia仓库存储token
            //由于pinia|vuex存储数据其实利用js对象
            token.value = result.data as string;
            console.log(token.value)
            //本地存储持久化存储一份
            localStorage.setItem("token", token.value as string)
            //保证当前async函数返回一个成功的promise函数
            return 'ok'
        } else {
            return Promise.reject(new Error(result.data))
        }
    }
    //获取用户信息方法
    async function userInfo() {
        //获取用户信息进行存储
        const result: userInfoResponseData = await reqUserInfo()
        console.log(result)

        if (result.code == 200) {
            username.value = result.data.name
            avatar.value = result.data.avatar
            return 'ok';
        } else {
            return Promise.reject(new Error(result.message))
        }
    }
    //退出登录
    async function userLogout() {
        const result: any = await reqLogout()
        if (result.code == 200) {
            //本地数据清空
            token.value = ''
            username.value = ''
            avatar.value = ''
            localStorage.removeItem("token")
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    }

    return {
        token,
        menuRoutes,
        username,
        avatar,
        userLogin,
        userInfo,
        userLogout
    }
})
//对外暴露小仓库
export default useUserStore;
